package org.lzy.shop.adapter

import android.content.Context
import android.graphics.Bitmap
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder

import org.lzy.shop.R
import java.lang.ref.WeakReference
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.math.min

class ChoosePicAdapter(context: Context, maxNum: Int = 9) :
    BaseQuickAdapter<Bitmap, QuickViewHolder>() {

    private val contextRef: WeakReference<Context> = WeakReference(context)
    private val maxImageCount: Int = maxNum
    private val imageItems = CopyOnWriteArrayList<Bitmap>()
    private var onAddPicturesListener: OnAddPicturesListener? = null
    private var showAddButton: Boolean = true

    //构造函数初始化
    init {
        //设置数据
        submitList(arrayListOf())
    }

    //创建ViewHolder
    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
        return QuickViewHolder(R.layout.item_trouble_photo, parent)
    }

    override fun onBindViewHolder(
        holder: QuickViewHolder,
        position: Int,
        item: Bitmap?
    ) {
        val rl_kuang: RelativeLayout = holder.getView(R.id.item_gv_photo_rl_kuang)
        val sivPhoto: ImageView = holder.getView(R.id.siv_photo)
        val iv_delete: ImageView = holder.getView(R.id.iv_delete)

        // 检查是否是添加按钮位置
        if (showAddButton && position == itemCount - 1 && itemCount <= maxImageCount) {
            //显示添加按钮
            rl_kuang.visibility = View.GONE
            sivPhoto.setImageResource(R.drawable.add_photo)
            iv_delete.visibility = View.GONE

            sivPhoto.setOnClickListener {
                onAddPicturesListener?.onAdd()
            }
        } else {
            //显示图片
            rl_kuang.visibility = View.VISIBLE
            iv_delete.visibility = View.VISIBLE

            //获取Bitmap并显示
            val bitmap = getItem(position)
            if (bitmap != null) {
                sivPhoto.setImageBitmap(bitmap)
            } else {
                //图片已被回收，显示占位图
                sivPhoto.setImageResource(R.drawable.ic_launcher_background)
            }

            //设置删除按钮点击事件
            iv_delete.setOnClickListener {
                onAddPicturesListener?.delete(position)
            }
        }
    }

    //设置监听器
    fun setOnAddPicturesListener(listener: OnAddPicturesListener) {
        this.onAddPicturesListener = listener
    }

    //添加单张图片
    fun addImage(bitmap: Bitmap?) {
        if (bitmap == null || imageItems.size >= maxImageCount) {
            return
        }

        try {
            //压缩图片
            val compressedBitmap = compressBitmap(bitmap)
            imageItems.add(compressedBitmap)

            //更新数据
            updateData()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //批量添加图片
    fun addImages(bitmaps: List<Bitmap>) {
        if (bitmaps.isEmpty() || imageItems.size >= maxImageCount) {
            return
        }

        val remainingSlots = maxImageCount - imageItems.size
        val actualCount = min(bitmaps.size, remainingSlots)

        try {
            for (i in 0 until actualCount) {
                val bitmap = bitmaps[i]
                val compressedBitmap = compressBitmap(bitmap)
                imageItems.add(compressedBitmap)
            }

            //更新数据
            updateData()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //移除图片
    fun removeImage(position: Int) {
        if (position >= 0 && position < imageItems.size) {
            //回收Bitmap资源
            val bitmap = imageItems[position]
            if (!bitmap.isRecycled) {
                bitmap.recycle()
            }

            //从列表中移除
            imageItems.removeAt(position)

            //更新数据
            updateData()
        }
    }

    //更新数据
    private fun updateData() {
        val data = ArrayList(imageItems)
        showAddButton = imageItems.size < maxImageCount
        submitList(data)
    }

    //获取所有图片
    val photoFiles: ArrayList<Bitmap> get() {
        return ArrayList(imageItems)
    }

    //压缩Bitmap，避免OOM
    private fun compressBitmap(bitmap: Bitmap): Bitmap {
        //计算目标尺寸，保持宽高比
        val maxWidth = 800
        val maxHeight = 800

        val originalWidth = bitmap.width
        val originalHeight = bitmap.height

        var targetWidth = originalWidth
        var targetHeight = originalHeight

        //如果图片过大，按比例缩小
        if (originalWidth > maxWidth || originalHeight > maxHeight) {
            val widthRatio = maxWidth.toFloat() / originalWidth
            val heightRatio = maxHeight.toFloat() / originalHeight
            val scaleRatio = min(widthRatio, heightRatio)

            targetWidth = (originalWidth * scaleRatio).toInt()
            targetHeight = (originalHeight * scaleRatio).toInt()
        }

        //如果缩小比例不大，直接返回原图片
        if (targetWidth == originalWidth && targetHeight == originalHeight) {
            return bitmap
        }

        try {
            //创建缩放后的 bitmap
            return Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true)
        } catch (e: OutOfMemoryError) {
            //处理OOM异常
            System.gc()
            try {
                return Bitmap.createScaledBitmap(bitmap, targetWidth / 2, targetHeight / 2, true)
            } catch (e2: Exception) {
                //如果仍然失败，返回一个很小的占位图
                return Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
            }
        }
    }

    //释放所有资源
    fun releaseResources() {
        //回收所有Bitmap资源
        for (bitmap in imageItems) {
            if (!bitmap.isRecycled) {
                bitmap.recycle()
            }
        }

        //清空列表
        imageItems.clear()
        submitList(null)

        //清空监听器引用
        onAddPicturesListener = null
    }

    //图片选择事件监听器接口
    interface OnAddPicturesListener {
        //添加图片
        fun onAdd()
        //删除指定位置的图片
        fun delete(position: Int)
    }



    override fun getItemCount(items: List<Bitmap>): Int {
        val count = items.size
        return if (showAddButton && count < maxImageCount) count + 1 else count
    }

    override fun getItemViewType(position: Int, list: List<Bitmap>): Int {
        return if (showAddButton && position == itemCount - 1 && itemCount <= maxImageCount) {
            1 // 添加按钮类型
        } else {
            0 // 图片类型
        }
    }
}